const net = require('net');
const fs = require('fs');
const globalConf = require('./conf');
const server = net.createServer();

server.listen(globalConf.port, '127.0.0.1');
server.on('listening', () => console.log('Server start.'));
server.on('connection', (socket) => {
  console.log('new connection');
  socket.on('data', (data) => {
    const requestHeader = data.toString();
    /**
     * console.log(requestHeader);
     *  GET /index.html?msg=haveyouate HTTP/1.1
        Host: localhost:8000
        Connection: keep-alive
        Cache-Control: max-age=0
        sec-ch-ua: "Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"
        sec-ch-ua-mobile: ?0
        sec-ch-ua-platform: "Windows"
        Upgrade-Insecure-Requests: 1
        ...
     */
    const firstLine = requestHeader.split('\r\n')[0];
    // console.log(firstLine);
    //GET /index.html?msg=haveyouate HTTP/1.1

    // console.log(firstLine.split(' '));
    //[ 'GET', '/index.html?msg=haveyouate', 'HTTP/1.1' ]

    const url = firstLine.split(' ')[1].split('?')[0];
    // console.log(url);
    ///index.html

    try {
      // console.log(__dirname);
      //C:\frontEnd\exercise\nodejs-exercise
      const indexPage = fs.readFileSync(__dirname + globalConf.path + url);
      /**
     console.log(indexPage.toString());
     * <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>Document</title>
          <link rel="stylesheet" href="./index.css" />
        </head>
        <body>
          <div class="app">Hello</div>
        </body>
      </html>
     */

      //给浏览器发送消息
      //注意字符串拼接返回的index.html在浏览器是无法正常加载图片的，因为图片转字符串时会出现乱码
      //解决方案是除了给浏览器返回响应头信息，另外需要响应直接将读取index.html文件后的buffer给浏览器
      // socket.write(`HTTP 200OK\r\nContentType: text/html\r\n\r\n${indexPage}`);
      socket.write('HTTP 200OK\r\nContentType: text/html\r\n\r\n');
      socket.write(indexPage);
    } catch (e) {
      const notFoundPage = fs
        .readFileSync(__dirname + globalConf.path + '/404.html')
        .toString();
      socket.write(
        'HTTP 404NotFound\r\nContentType: text/html\r\n\r\n' + notFoundPage
      );
    }

    socket.end();
  });
});
